package com.hm.fast.auto.su;

import com.hm.fast.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;
import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * @author shishun.wang
 * @version 1.0
 * @date 2019/3/17 23:58
 * @describe
 */
@Slf4j
@Repository
public class BaseDaoImpl<T,ID extends Serializable> implements BaseDao<T,ID> {

    @PersistenceContext
    private EntityManager entityManager;

   /* @Override
    public List<Object[]> selectBySQL(String sql) {
        return entityManager.createNativeQuery(sql).getResultList();
    }*/

    @Override
    public boolean existsBySQL(String sql) {
        return CommonUtil.isNotEmpty(entityManager.createNativeQuery(sql).getResultList());
    }

    @Override
    @Transactional
    public void updateBySQL(String sql) {
        entityManager.createNativeQuery(sql).executeUpdate();
    }

    @Override
    @Transactional
    public void deleteBySQL(String sql) {
        entityManager.createNativeQuery(sql).executeUpdate();
    }

    @Override
    public void delete(Class<?> clazz, Long id) {
        /*Object reference = entityManager.getReference(clazz, id);
        if (null != reference) entityManager.remove(reference);*/
        T reference = this.findOne(clazz, id);
        if (null != reference) entityManager.remove(reference);
    }

    @Override
    public T findOne(Class<?> clazz, Long id) {
        return (T) entityManager.find(clazz,id);
    }

    @Override
    @Transactional
    public void save(T entity) {
        entityManager.persist(entity);
    }

    @Override
    @Transactional
    public void update(T entity) {
        entityManager.merge(entity);
    }

    @Override
    public Map<String, Object> findOneBySQL(String sql) {
        Query query = entityManager.createNativeQuery(sql);
        query.unwrap(org.hibernate.Query.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String, Object>> result = query.getResultList();
        if (CommonUtil.isNotEmpty(result)){
            return result.get(0);
        }
        return null;
    }

    @Override
    public List<Map<String, Object>> findListBySQL(String sql) {
        Query query = entityManager.createNativeQuery(sql);
        query.unwrap(org.hibernate.Query.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        return query.getResultList();
    }

    @Override
    public int countBySQL(String sql) {
        return entityManager.createNativeQuery(sql).getFirstResult();
    }
}
